// FriendGroupServiceImpl.java
package com.baoyouqun.API.friend;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cola.dto.MultiResponse;
import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baoyouqun.API.IM.TencentImService;
import com.baoyouqun.API.friend.domain.*;
import com.baoyouqun.entity.User;
import com.baoyouqun.mapper.FriendGroupMapper;
import com.baoyouqun.mapper.FriendGroupMemberMapper;
import com.baoyouqun.service.UserResourceService;
import com.baoyouqun.service.UserService;
import com.baoyouqun.service.UserVipTimeService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FriendGroupServiceImpl extends ServiceImpl<FriendGroupMapper, FriendGroup> implements FriendGroupService {

    @Resource
    private FriendGroupMapper friendGroupMapper;

    @Resource
    private FriendGroupMemberMapper friendGroupMemberMapper;

    @Resource
    private FriendService friendService;

    @Resource
    private UserService userService;

    @Resource
    private UserVipTimeService userVipTimeService;

    @Resource
    private TencentImService tencentImService;

    @Resource
    private UserResourceService userResourceService;

    @Override
    public MultiResponse<FriendGroupVO> getFriendGroups() {
        String userId = StpUtil.getLoginIdAsString();

        // 获取所有分组
        List<FriendGroup> groups = friendGroupMapper.selectList(
                new LambdaQueryWrapper<FriendGroup>()
                        .eq(FriendGroup::getUserId, userId)
                        .orderByAsc(FriendGroup::getCreateTime)
        );

        if (CollUtil.isEmpty(groups)) {
            return MultiResponse.of(Collections.emptyList());
        }

        List<FriendGroupVO> result = new ArrayList<>();
        for (FriendGroup group : groups) {
            FriendGroupVO vo = new FriendGroupVO();
            vo.setId(group.getId());
            vo.setGroupName(group.getGroupName());

            // 获取分组内好友
            List<FriendGroupMember> members = friendGroupMemberMapper.selectList(
                    new LambdaQueryWrapper<FriendGroupMember>()
                            .eq(FriendGroupMember::getGroupId, group.getId())
            );

            if (CollUtil.isNotEmpty(members)) {
                List<String> friendIds = members.stream()
                        .map(FriendGroupMember::getFriendId)
                        .collect(Collectors.toList());
                vo.setFriendCount(friendIds.size());

                // 组装好友信息
                vo.setFriends(assembleFriendVOs(friendIds));
            } else {
                vo.setFriendCount(0);
                vo.setFriends(Collections.emptyList());
            }

            result.add(vo);
        }

        return MultiResponse.of(result);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SingleResponse<String> addFriendGroup(AddFriendGroupCmd cmd) {
        String userId = StpUtil.getLoginIdAsString();

        // 检查分组名称是否已存在
        long count = friendGroupMapper.selectCount(
                new LambdaQueryWrapper<FriendGroup>()
                        .eq(FriendGroup::getUserId, userId)
                        .eq(FriendGroup::getGroupName, cmd.getGroupName())
        );

        if (count > 0) {
            return SingleResponse.buildFailure("50010", "分组名称已存在");
        }

        FriendGroup group = new FriendGroup();
        group.setUserId(userId);
        group.setGroupName(cmd.getGroupName());
        group.setCreateTime(LocalDateTime.now());
        group.setUpdateTime(LocalDateTime.now());

        friendGroupMapper.insert(group);
        return SingleResponse.of(group.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response updateFriendGroup(UpdateFriendGroupCmd cmd) {
        String userId = StpUtil.getLoginIdAsString();

        // 检查分组是否存在且属于当前用户
        FriendGroup group = friendGroupMapper.selectOne(
                new LambdaQueryWrapper<FriendGroup>()
                        .eq(FriendGroup::getId, cmd.getGroupId())
                        .eq(FriendGroup::getUserId, userId)
        );

        if (group == null) {
            return Response.buildFailure("50011", "分组不存在或无权操作");
        }

        // 更新分组名称
        if (StrUtil.isNotBlank(cmd.getGroupName())) {
            // 检查新名称是否已存在
            long count = friendGroupMapper.selectCount(
                    new LambdaQueryWrapper<FriendGroup>()
                            .eq(FriendGroup::getUserId, userId)
                            .eq(FriendGroup::getGroupName, cmd.getGroupName())
                            .ne(FriendGroup::getId, cmd.getGroupId())
            );

            if (count > 0) {
                return Response.buildFailure("50010", "分组名称已存在");
            }

            group.setGroupName(cmd.getGroupName());
            group.setUpdateTime(LocalDateTime.now());
            friendGroupMapper.updateById(group);
        }

        // 处理新增好友
        if (CollUtil.isNotEmpty(cmd.getAddFriendIds())) {
            // 验证是否是好友关系
            List<String> validFriendIds = validateFriends(userId, cmd.getAddFriendIds());

            // 批量添加
            List<FriendGroupMember> members = validFriendIds.stream().map(friendId -> {
                FriendGroupMember member = new FriendGroupMember();
                member.setGroupId(cmd.getGroupId());
                member.setFriendId(friendId);
                return member;
            }).collect(Collectors.toList());

            friendGroupMemberMapper.insert(members);
        }

        // 处理移除好友
        if (CollUtil.isNotEmpty(cmd.getRemoveFriendIds())) {
            friendGroupMemberMapper.delete(
                    new LambdaQueryWrapper<FriendGroupMember>()
                            .eq(FriendGroupMember::getGroupId, cmd.getGroupId())
                            .in(FriendGroupMember::getFriendId, cmd.getRemoveFriendIds())
            );
        }

        return Response.buildSuccess();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Response deleteFriendGroup(String groupId) {
        String userId = StpUtil.getLoginIdAsString();

        // 检查分组是否存在且属于当前用户
        FriendGroup group = friendGroupMapper.selectOne(
                new LambdaQueryWrapper<FriendGroup>()
                        .eq(FriendGroup::getId, groupId)
                        .eq(FriendGroup::getUserId, userId)
        );

        if (group == null) {
            return Response.buildFailure("50011", "分组不存在或无权操作");
        }

        // 先删除分组内成员
        friendGroupMemberMapper.delete(
                new LambdaQueryWrapper<FriendGroupMember>()
                        .eq(FriendGroupMember::getGroupId, groupId)
        );

        // 再删除分组
        friendGroupMapper.deleteById(groupId);
        return Response.buildSuccess();
    }

    /**
     * 验证好友关系并返回有效好友ID
     */
    private List<String> validateFriends(String userId, List<String> friendIds) {
        if (CollUtil.isEmpty(friendIds)) {
            return Collections.emptyList();
        }

        // 查询已通过的好友关系
        List<FriendRelation> relations = ((FriendServiceImpl) friendService).list(
                new LambdaQueryWrapper<FriendRelation>()
                        .eq(FriendRelation::getUserId, userId)
                        .in(FriendRelation::getFriendId, friendIds)
                        .eq(FriendRelation::getStatus, 1)
        );

        return relations.stream()
                .map(FriendRelation::getFriendId)
                .collect(Collectors.toList());
    }

    /**
     * 组装好友VO列表
     */
    private List<FriendVO> assembleFriendVOs(List<String> friendIds) {
        if (CollUtil.isEmpty(friendIds)) {
            return Collections.emptyList();
        }

        // 获取好友用户信息
        Map<String, User> userMap = userService.listByIds(friendIds).stream()
                .collect(Collectors.toMap(User::getId, user -> user));

        // 获取VIP状态
        Map<String, Boolean> vipStatusMap = userVipTimeService.getVipStatusByUserIds(friendIds);

        // 获取在线状态
        Set<String> onlineStatusMap = tencentImService.getOnlineUserIds();

        // 获取用户资源和需求信息
        Map<String, List<String>> userResourcesMap = userResourceService.getUserResourcesMap(friendIds);
        Map<String, List<String>> userNeedsMap = userResourceService.getUserNeedsMap(friendIds);

        // 获取好友关系备注
        String userId = StpUtil.getLoginIdAsString();
        List<FriendRelation> relations = ((FriendServiceImpl) friendService).list(
                new LambdaQueryWrapper<FriendRelation>()
                        .eq(FriendRelation::getUserId, userId)
                        .in(FriendRelation::getFriendId, friendIds)
        );
        Map<String, String> remarkMap = relations.stream()
                .collect(Collectors.toMap(
                        FriendRelation::getFriendId,
                        // 备注为 null 时用空字符串替代
                        fr -> Optional.ofNullable(fr.getRemark()).orElse(""),
                        (existing, replacement) -> existing
                ));

        List<FriendVO> friends = new ArrayList<>();
        for (String friendId : friendIds) {
            User friend = userMap.get(friendId);
            if (friend == null) continue;

            FriendVO friendVO = new FriendVO();
            friendVO.setId(friend.getId());
            friendVO.setName(StrUtil.isNotBlank(remarkMap.get(friendId)) ? remarkMap.get(friendId) : friend.getName());
            friendVO.setHeadImg(friend.getHeadImg());
            friendVO.setIsVip(vipStatusMap.getOrDefault(friend.getId(), false));
            friendVO.setOnline(onlineStatusMap.contains(friend.getId()));
            friendVO.setProvince(friend.getProvince());
            friendVO.setCity(friend.getCity());
            friendVO.setDistrict(friend.getDistrict());

            // 设置资源信息
            List<String> resources = userResourcesMap.getOrDefault(friend.getId(), Collections.emptyList());
            friendVO.setResourceCount(resources.size());
            friendVO.setTopResources(resources.stream().limit(3).collect(Collectors.toList()));

            // 设置需求信息
            List<String> needs = userNeedsMap.getOrDefault(friend.getId(), Collections.emptyList());
            friendVO.setNeedCount(needs.size());
            friendVO.setTopNeeds(needs.stream().limit(3).collect(Collectors.toList()));

            friendVO.setRemark(remarkMap.get(friendId));

            friends.add(friendVO);
        }

        return friends;
    }
}